package com.wxp.mvc.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wxp.mvc.Action;
import com.wxp.mvc.ActionForm;
import com.wxp.mvc.XmlBean;
import com.wxp.mvc.util.FullForm;
import com.wxp.mvc.util.XmlParse;

public class ActionServlet extends HttpServlet {

	private static final long serialVersionUID = 4981065648416225376L;

	@SuppressWarnings("rawtypes")
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String requestUri = this.getUri(request);
		InputStream in = request.getServletContext()
				.getResourceAsStream("/WEB-INF/classes/" + this.getInitParameter("strtus-config"));
		try {
			Map<String, XmlBean> map = XmlParse.parseXml(in);
			XmlBean xmlBean = map.get(requestUri);
			String formClass = xmlBean.getFormClass();
			Map<String, String> resultMap = xmlBean.getResultMap();
			ActionForm form = FullForm.full(formClass, request);
			String actionClass = xmlBean.getActionClass();
			Class clazz = Class.forName(actionClass);
			Action action = (Action) clazz.newInstance();
			String result = action.execute(request, response, form);
			String url = resultMap.get(result);
			RequestDispatcher dispatcher = request.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	private String getUri(HttpServletRequest request) {
		String uri = request.getServletPath();
		return uri.split("\\.")[0];
	}

}
